<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item prop="query">
        <el-input v-model="queryParams.query" placeholder="请输入打印机编号（SN码）/公开码/打印机名称" clearable @keyup.enter="handleQuery"
          style="width: 350px" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['manage:printer:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:printer:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="Download" @click="handleExport"
          v-hasPermi="['manage:printer:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="pointer" @click="handleSync"
          v-hasPermi="['manage:printer:sync']">同步</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="printerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column label="打印机编号" align="center" prop="sn" />
      <el-table-column label="公开码" align="center" prop="publicCode" />
      <el-table-column label="打印机名称" align="center" prop="name" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="manage_printer_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="切刀" align="center" prop="cutKnifeEnable">
        <template #default="scope">
          <span>{{ scope.row.cutKnifeEnable || '无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="固件版本" align="center" prop="version" />
      <el-table-column label="添加时间" align="center" prop="bindTime" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="warning" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:printer:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:printer:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.limit"
      @pagination="getList" />

    <!-- 添加打印机对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="printerRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="打印机编号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入打印机编号" />
        </el-form-item>

        <el-form-item label="打印机名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入打印机名称" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改打印机对话框 -->
    <el-dialog :title="title" v-model="openModify" width="550px" append-to-body>
      <el-form ref="printerRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="打印机编号" prop="sn">
          <el-input v-model="form.sn" disabled placeholder="请输入打印机编号" />
        </el-form-item>

        <el-form-item label="来单语音设置:" prop="voiceType" label-width="120px">
          <el-select v-model="form.voiceType" placeholder="请选择来单语音:" clearable>
            <el-option v-for="dict in manage_printer_voiceType" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="打印机音量设置:" prop="volumeLevel" label-width="120px">
          <el-select v-model="form.volumeLevel" placeholder="请选择打印机音量:" clearable>
            <el-option v-for="dict in manage_printer_volumeLevel" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="modifyVoice">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Printer" lang="ts">
import { addPrinters, deletePinter, getPrinterList, setVoiceType, syncPinter } from '@/api/manage/printer';
import { ElForm, ElMessage } from 'element-plus';
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';
import usePinter from '@/api/request/manage/pinter/index';

const { proxy } = getCurrentInstance() as any;

const printerList = ref([]);
const open = ref(false);
const openModify = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<string[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const { manage_printer_status } = proxy.useDict('manage_printer_status');
const { manage_printer_voiceType } = proxy.useDict('manage_printer_voiceType');
const { manage_printer_volumeLevel } = proxy.useDict('manage_printer_volumeLevel');


const data = reactive({
	form: {} as any,
	queryParams: {
		page: 1,
		limit: 10,
		query: ''
	},
	rules: {
		sn: [
			{ required: true, message: '请输入打印机编号', trigger: 'blur' },
		],
		name: [
			{ required: true, message: '请输入打印机名称', trigger: 'blur' },
		],
	}
});
const queryRef = ref<InstanceType<typeof ElForm>>();
const { queryParams, form, rules } = toRefs(data);

const { handlePrinter } = usePinter();

/** 查询打印机列表 */
async function getList() {
	loading.value = true;
	const res = await getPrinterList(queryParams.value);
	console.log(res, '获取打印机列表 ');
	printerList.value = res.data.rows;
	total.value = res.data.total;
	loading.value = false;
}

// 取消按钮
function cancel() {
	open.value = false;
	openModify.value = false;
	reset();
}

// 表单重置
function reset() {
	form.value = {
		id: null, printerName: null, printerType: null, developerName: null, developerSecretkey: null, printerNumber: null, printerKey: null, printerCount: null, isopenPrintReceipt: null, isFontBold: null, fontSize: null, isDelete: null, createBy: null, createTime: null, updatedBy: null, updatedTime: null
	};
	proxy.resetForm('printerRef');
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.page = 1;
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm(queryRef);
	handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: { map: (arg0: (item: any) => any) => never[]; length: number; }) {
	ids.value = selection.map((item: { sn: string; }) => item.sn);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
	console.log(ids.value, single.value, multiple.value);
}

/** 新增按钮操作 */
async function handleAdd() {
	reset();
	open.value = true;
	title.value = '添加打印机';
}

/** 修改按钮操作 */
function handleUpdate(row: any) {
	reset();
	console.log(row, '----');
	form.value = row;
	openModify.value = true;
	title.value = '修改打印机';
}

/** 提交按钮 */
function submitForm() {
	proxy.$refs['printerRef'].validate(async (valid: any) => {
		if (valid) {
			const params = { items: [{ ...form.value }] };
			try {
				const res: any = await addPrinters(params);
				console.log('新增打印机:', res);
				if (res.fail.length > 0) {
					ElMessage.error('新增打印机失败');
				}
				if (res.success.length > 0) {
					proxy.$modal.msgSuccess('新增成功');
					getList();
					open.value = false;

				}
			} catch (error) {
				ElMessage.error('新增打印机失败');
			}
		}
	});
}
async function handleSync(){
	try {
	  const res = await getPrinterList({page:1,limit:5000,query:''});
		const syncData = res.data.rows.map((ele:any)=>({printerKey:ele.sn,printerName:ele.name}));
		await syncPinter({xqPrinters: syncData});
		ElMessage.success('同步成功！');
	} catch (error) {
		ElMessage.error('同步失败，请检查网络');
	}
}
/**
 * 修改声音
 */
async function modifyVoice() {
	const params = {
		sn: form.value.sn,
		voiceType: form.value.voiceType,
		volumeLevel: form.value.volumeLevel,
	};
	const res = await setVoiceType(params);
	console.log(res, '修改打印机声音：');
	if (res) {
		ElMessage.success('修改声音成功');
		getList();
	} else {
		ElMessage.error('修改声音失败！');
	}
	openModify.value = false;
}
/**
 * 删除按钮操作
 * @param row {Object | Array} 
 * @param type { 'single' | 'multiple' }
 */
function handleDelete(row: any) {
	const idsName = row.sn || ids.value;
	proxy.$modal.confirm(`是否确认删除打印机编号为:"${idsName}"的数据项？`).then(async () => {
		const res: any = await deletePinter({ snlist: [idsName] });
		console.log('删除打印机', res);
		if (res.fail.length > 0) {
			ElMessage.error('删除成功');
		}
		if (res.success.length > 0) {
			getList();
			proxy.$modal.msgSuccess('删除成功');
		}
	}).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
	proxy.download('manage/printer/exportByStream', {
		...queryParams.value
	}, `printer_${new Date().getTime()}.xlsx`);
}



getList();
</script>